import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/LoginPage.vue')
    },
    {
      path: '/register',
      component: () => import('@/views/login/RegisterPage.vue')
    },
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/home/HomePage.vue')
        },
        {
          path: '/project',
          component: () => import('@/views/project/ProjectPage.vue')
        },
        {
          path: '/user',
          component: () => import('@/views/user/UserPage.vue')
        }
      ]
    },
    {
      path: '/user/info',
      component: () => import('@/views/user/UserInfoManage.vue')
    },
    {
      path: '/user/car',
      component: () => import('@/views/user/UserCarManage.vue')
    },
    {
      path: '/user/feedback',
      component: () => import('@/views/user/UserFeedbackManage.vue')
    },
    {
      path: '/user/business',
      component: () => import('@/views/user/UserBusinessManage.vue')
    }
  ]
})

// 登录注册访问拦截
router.beforeEach((to) => {
  const userStore = useUserStore()
  if (!userStore.token && to.path !== '/login' && to.path !== '/register') {
    showNotify({ type: 'warning', message: '请先登录' })
    return '/login'
  }
  if (userStore.token && (to.path === '/login' || to.path === '/register')) {
    showNotify({ type: 'success', message: '已登录' })
    return '/'
  }
})

export default router
